package cc.flybb.viewmodelshp;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.SavedStateHandle;

public class MyViewModel extends AndroidViewModel {
    private SavedStateHandle handle;//SavedStateHandle 类 ,  它使您的 ViewModel 类能够访问和促成已保存状态。您可以在 ViewModel 类的构造函数以及 Fragment 默认提供的工厂中接收此对象，并且 AppCompatActivity 会自动注入 SavedStateHandle。
    private String key = getApplication().getResources().getString(R.string.shp_name);
    private String shpName = getApplication().getResources().getString(R.string.shp_name);

    public MyViewModel(@NonNull Application application,SavedStateHandle handle) {
        super(application);
        this.handle = handle;
        if(!handle.contains(key)){
            load();
        }
    }

    public LiveData<Integer> getNumber(){
        return handle.getLiveData(key);
    }
    protected void load() {
        SharedPreferences shp = getApplication().getSharedPreferences(shpName,Context.MODE_PRIVATE);
        int x = shp.getInt(key,0 );
        handle.set(key,x);
    }

    protected void save(){
        SharedPreferences shp = getApplication().getSharedPreferences(shpName,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = shp.edit();
        editor.putInt(shpName,100);
        editor.commit();
    }

    // 传进来+1或者-1
    public void add(int x){
        handle.set(key,getNumber().getValue()+x);
        //        save();
    }

}
